<template>
  <div class="event-report-page page">
    <nav-bar title="事件上报" theme="white" message></nav-bar>
    <div class="event-report-main page-main" style="margin-top: 44px">
      <van-sticky class="page-scroll" :offset-top="44">
        <van-form
          validate-trigger="onSubmit"
          :show-error="false"
          ref="from"
          input-align="right"
          error-message-align="right"
          :label-width="120"
          @failed="onFailed"
          @submit="onSubmit"
        >
          <van-field
            required
            name="eventName"
            v-model="formParams.eventName"
            label="事件名称"
            placeholder="请输入"
            right-icon="arrow"
            class="van-field__right-icon-white"
            :maxlength="50"
            :rules="rules.eventName"
          />
          <van-field
            required
            readonly
            clickable
            name="eventTypeName"
            v-model="formParams.eventTypeName"
            label="事件类型"
            placeholder="请选择"
            right-icon="arrow"
            :rules="rules.eventTypeName"
            @click="cascadeOpenPopup('eventType', '事件类型')"
          />
          <van-field
            required
            readonly
            clickable
            name="eventScaleName"
            v-model="formParams.eventScaleName"
            label="事件规模"
            placeholder="请选择"
            right-icon="arrow"
            :rules="rules.eventScaleName"
            @click="dictOpenPopup('eventScale')"
          />
          <van-field required label="事件描述" readonly :border="false" />
          <van-field
            required
            name="eventDescription"
            v-model="formParams.eventDescription"
            placeholder="请对您要上报的内容进行具体描述……"
            rows="5"
            autosize
            type="textarea"
            show-word-limit
            :border="false"
            input-align="left"
            class="van-field__value--textarea"
            maxlength="200"
            :rules="rules.eventDescription"
          />
          <van-field
            required
            readonly
            clickable
            name="communityRegionName"
            v-model="formParams.communityRegionName"
            label="所属区域"
            placeholder="请选择"
            right-icon="arrow"
            :rules="rules.communityRegionName"
            @click="cascadeOpenPopup('communityRegion', '所属区域')"
          />
          <van-field
            required
            name="eventLocation"
            v-model="formParams.eventLocation"
            label="事件点位"
            placeholder="请输入"
            right-icon="arrow"
            class="van-field__right-icon-white"
            maxlength="100"
            :rules="rules.eventLocation"
            @click="openMap"
          />
          <van-field label="添加图片/视频" readonly :border="false">
            <template #input>
              <van-radio-group v-model="accept" direction="horizontal">
                <van-radio name="image/*">图片</van-radio>
                <van-radio name="video/*">视频</van-radio>
              </van-radio-group>
            </template>
          </van-field>
          <van-field class="van-field__value--upload" input-align="left">
            <template #input>
              <van-uploader
                name="fileList"
                v-model="fileList"
                max-count="9"
                :accept="accept"
                :max-size="maxSize"
                :preview-image="previewImage"
                :before-read="uploadBeforeRead"
                :after-read="uploadAfterRead"
                @click-preview="previewClick"
              >
                <template #preview-cover="file">
                  <div v-if="format.includes(file.file.name.split('.')[file.file.name.split('.').length - 1])">
                    <div class="van-uploader__preview-masker"></div>
                    <video-player
                      class="video-player vjs-custom-skin"
                      :playsinline="true"
                      :options="{
                        aspectRatio: '16:16',
                        sources: [
                          {
                            src: $config.ImageURl + file.file.url
                          }
                        ]
                      }"
                    ></video-player>
                  </div>
                </template>
                <div class="van-uploader__input--white">
                  <div class="van-uploader__input--content">
                    <div class="upload-image">
                      <img src="@/assets/images/basic/icon_camera@2x.png" />
                    </div>
                    <div class="upload-text">点击拍摄</div>
                  </div>
                </div>
              </van-uploader>
            </template>
          </van-field>
          <van-field name="switch" label="是否公开">
            <template #input>
              <van-switch v-model="formParams.isExposure" active-value="1" inactive-value="2" size="22" />
            </template>
          </van-field>
          <van-field name="switch" label="是否可自行处理">
            <template #input>
              <van-switch v-model="formParams.isDisposal" active-value="1" inactive-value="2" size="22" />
            </template>
          </van-field>
          <div style="margin: 60px 16px">
            <van-row :gutter="23">
              <van-col span="12">
                <van-button block native-type="button" @click="onClear">清空</van-button>
              </van-col>
              <van-col span="12">
                <van-button block type="info" native-type="submit" :disabled="buttonDisabled">提交</van-button>
              </van-col>
            </van-row>
          </div>
        </van-form>
      </van-sticky>
    </div>
    <!-- 字典项 -->
    <van-popup v-model="dictPopupShow" round position="bottom" @close="dictValue = ''">
      <van-picker
        show-toolbar
        :default-index="dictData[dictType] && dictData[dictType].findIndex(o => o.code === dictValue)"
        :columns="dictData[dictType]"
        value-key="description"
        @cancel="dictPopupShow = false"
        @confirm="dictOnConfirm"
      />
    </van-popup>
    <!-- 联级 -->
    <van-popup v-model="cascadePopupShow" round position="bottom" @close="cascadeValue = ''">
      <van-cascader
        v-model="cascadeValue"
        :title="cascadeTitle"
        :options="cascadeData[cascadeType]"
        :field-names="fieldNames[cascadeType]"
        :closeable="false"
        @finish="cascadeOnFinish"
      />
    </van-popup>
    <!-- 视频预览 -->
    <gb-video :url="videoUrl" :show.sync="videoPopupShow"></gb-video>
  </div>
</template>
<script>
import { mapState } from 'vuex'
import Event from '@/api/event'
import General from '@/api/general'
import { AddForm } from './libs/data'
import Upload from '@/mixins/upload'
import SelectPopup from '@/mixins/selectPopup'
export default {
  mixins: [Upload, SelectPopup],
  data() {
    return {
      folder: 'event',
      accept: 'image/*',
      maxSize: 50 * 1024 * 1024,
      fileList: [],
      dictTypes: 'eventScale',

      buttonDisabled: false,
      formParams: new AddForm(),
      rules: {
        eventName: [
          { required: true, message: '请输入事件名称' },
          {
            validator: val => {
              return val.length >= 5
            },
            message: '事件名称至少输入5个字'
          }
        ],
        eventTypeName: [{ required: true, message: '请选择事件类型' }],
        eventScaleName: [{ required: true, message: '请选择事件规模' }],
        eventDescription: [
          { required: true, message: '请输入事件描述' },
          {
            validator: val => {
              return val.length >= 10
            },
            message: '事件描述至少输入10个字'
          }
        ],
        communityRegionName: [{ required: true, message: '请选择所属区域' }],
        eventLocation: [{ required: true, message: '请输入事件点位' }]
      },
      uploadKeys: [
        'firstImageUrl',
        'secondImageUrl',
        'thirdImageUrl',
        'fourthImageUrl',
        'fifthImageUrl',
        'sixthImageUrl',
        'seventhImageUrl',
        'eighthImageUrl',
        'ninthImageUrl'
      ],
      fieldNames: {
        eventType: { text: 'label' },
        communityRegion: { text: 'title', value: 'code' }
      },
      format: ['mp4', 'avi', 'mov'],
      videoPopupShow: false,
      videoUrl: '',
      regionCode: '',
      mapShow: false,
      mapData: null
    }
  },
  computed: {
    ...mapState({
      user: state => state.userInfo
    })
  },
  created() {
    this.formParams.communityRegion = this.user.regionCode
    this.formParams.communityRegionName = this.user.regionCodeName
    this.formParams.reportPerson = this.user.userName
    this.formParams.eventOrigin = '2'
    // 信息带入
    const paramsKeys = Object.keys(this.$route.params)
    if (paramsKeys.length) {
      for (let i = 0; i < paramsKeys.length; i++) {
        if (paramsKeys[i] === 'fileList') {
          this.fileList = this.$route.params.fileList
        } else if (this.$route.params[paramsKeys[i]]) {
          this.formParams[paramsKeys[i]] = this.$route.params[paramsKeys[i]]
        }
      }
    }
    // 获取行政区划
    this.getRegionCode()
    // 事件类型
    this.getEventType()
    // 所住区域
    // 字典项
    this.getDict(this.dictTypes)
    if (this.$route.params && this.$route.params.mapData) {
      this.mapData = this.$route.params.mapData
      this.formParams.eventLocation = this.mapData.adName
      this.formParams.longitude = this.mapData.longitude
      this.formParams.latitude = this.mapData.latitude
    }
    console.log(JSON.stringify(this.formParams))
  },
  methods: {
    // 获取行政区划
    async getRegionCode() {
      return await General.Region.getRegionCode({
        ip: document.location.host.indexOf('localhost') > -1 ? '188.188.33.24:86' : document.location.host
      }).then(res => {
        const { status, data } = res.data
        if (status === 0) {
          this.regionCode = data
          this.getTree()
        }
      })
    },
    // 视频预览
    previewClick({ file }, detail) {
      const urlArr = this.fileList[detail.index].url.split('.')
      const suffix = urlArr[urlArr.length - 1]
      if (this.format.includes(suffix)) {
        this.videoPopupShow = true
        this.videoUrl = this.$config.ImageURl + this.fileList[detail.index].url
      }
    },
    // 事件类型
    getEventType() {
      Event.Init.eventType().then(res => {
        const { status, data } = res.data
        if (status === 0) {
          this.cascadeData.eventType = data.eventTypeList
        }
      })
    },
    // 所住区域
    getTree() {
      General.Region.getTree({
        regionCode: this.regionCode
      }).then(res => {
        this.cascadeData.communityRegion = res.data.data
      })
    },
    // 校验失败
    onFailed(errorInfo) {
      this.$refs.from.scrollToField(errorInfo.errors[0].name)
    },
    // 上报成功
    onSubmit() {
      for (let i = 0; i < this.uploadKeys.length; i++) {
        this.formParams[this.uploadKeys[i]] = ''
      }
      for (let i = 0; i < this.fileList.length; i++) {
        this.formParams[this.uploadKeys[i]] = this.fileList[i].url
      }
      this.formParams.reportRegionCode = this.user.regionCode
      this.formParams.eventType = this.formParams.eventTypeCode
      this.buttonDisabled = true
      Event.Manage.save(this.formParams)
        .then(res => {
          const { status } = res.data
          if (status === 0) {
            this.$router.push('/page/message?backTo=-4&title=提交成功')
          } else {
            const eventTypeCode = this.formParams.eventType.split(',')
            this.formParams.eventType = eventTypeCode[eventTypeCode.length - 1]
            this.$toast.fail(res.data.message)
          }
          this.buttonDisabled = false
        })
        .catch(() => {
          this.buttonDisabled = false
        })
    },
    onClear() {
      this.$dialog
        .confirm({
          title: '提示',
          message: '是否清空所有内容',
          confirmButtonText: '是',
          cancelButtonText: '否'
        })
        .then(() => {
          this.formParams = new AddForm()
        })
    },
    openMap() {
      this.$router.push('/event/report/map')
    }
  }
}
</script>
